<script setup>
import { ElMessageBox, ElDrawer } from 'element-plus'
import { ElMessage } from 'element-plus'
import ChannelSelect from "@/views/article/components/ChannelSelect.vue";
import { ref } from 'vue'
import {Plus} from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import {articleAdd,articleDetail,articleUpdate} from '@/api/article'
import {baseURL} from '@/utils/request'
import axios from 'axios'
const imageUrl=ref('')
const visibleDrawer = ref(false)
const formRef = ref()
const editQ=ref()
const defaultForm = {
    title: '',
    cate_id: '',
    content: '',
    cover_img: '',
    state: '',
}
const emit=defineEmits(['success'])
const formModel = ref({
    ...defaultForm
})
const selectImg=(newFile)=>{
    imageUrl.value=URL.createObjectURL(newFile.raw)
    formModel.value.cover_img=newFile.raw
    
}
//暴漏方法
const open =async (row) => {
    visibleDrawer.value = true
    if (row.id) {
        const res=await articleDetail(row.id)
        formModel.value=res.data.data
        imageUrl.value=baseURL+formModel.value.cover_img
        urlToFile(imageUrl.value,formModel.value.cover_img)
    .then((file) => {
        formModel.value.cover_img = file;
    })
    .catch((error) => {
        console.error('转换失败:', error);
    });
    }
    else {
        formModel.value = { ...defaultForm }
        console.log('添加文章');
    }

}
//图片地址转换
const urlToFile = async (imageUrl, fileName) => {
    try {
        // 使用 axios 获取图片的二进制数据
        const response = await axios.get(imageUrl, { responseType: 'blob' });

        // 将 Blob 转换为 File
        const file = new File([response.data], fileName, { type: response.data.type });

        return file;
    } catch (error) {
        console.error('图片转换失败:', error);
        throw error;
    }
};
defineExpose({
    open,
})
const resetForm = () => {
    // 重置表单数据
    formModel.value = { ...defaultForm };

    // 清空图片预览
    imageUrl.value = '';

    // 清空富文本编辑器内容
 
        editQ.value.setHTML('');
    // 关闭抽屉
    visibleDrawer.value = false;
};
const rules = {
    title: [
        { required: true, message: '请输入文章标题', trigger: 'blur' },
    ],
    cate_id: [
        { required: true, message: '请选择文章分类', trigger: 'blur' },
    ],
};
const publicArticle = async (type) => {
    try{
        if(formModel.value.id){
            console.log('编辑操作')
            const ans=new FormData()
        for(const key in formModel.value){
            ans.append(key,formModel.value[key])
        }
        await articleUpdate(ans)
        ElMessage.success('文章更新成功!')
            visibleDrawer.value=false
            imageUrl.value=''
            editQ.value.setHTML('')
            emit('success','edit') 
        }
        else{
            formModel.value.state=type
        const ans=new FormData()
        for(const key in formModel.value){
            ans.append(key,formModel.value[key])
        }
        if(type==='已发布'){
ElMessage.success('文章已发布成功!')
        }
        else{
ElMessage.success('草稿稿件已生成!')
        }
          await articleAdd(ans)
            emit('success','add')
        }
        resetForm();
    }catch(error){
ElMessage.error('环境异常，请稍后再试')
console.error(error);
    }
   
       
};
</script>


<template>
    <el-drawer v-model="visibleDrawer" :title="formModel.id ? '编辑文章' : '添加文章'" direction="rtl" size="50%">
        <!-- 发表文章表单 -->
        <el-form :model="formModel" :rules="rules" ref="formRef" label-width="100px" >
            <el-form-item label="文章标题" prop="title">
                <el-input v-model="formModel.title" placeholder="请输入标题"></el-input>
            </el-form-item>
            <el-form-item label="文章分类" prop="cate_id">
                <ChannelSelect v-model="formModel.cate_id" width="100%"></ChannelSelect>
            </el-form-item>
            <el-form-item label="文章封面" prop="cover_img">
                <el-upload class="avatar-uploader"
                    :show-file-list="false"
                    :auto-upload="false"
                    :on-change="selectImg"  >
                    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus  />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="文章内容" prop="content">
                <div class="editor">
                    <quill-editor ref="editQ" theme="snow" v-model:content="formModel.content" content-type="html"></quill-editor>
                </div>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="publicArticle('已发布')">发布</el-button>
                <el-button type="info" @click="publicArticle('草稿')">草稿</el-button>
            </el-form-item>
        </el-form>
    </el-drawer>

</template>
<style lang="scss" scoped>
.avatar-uploader {
  display: inline-block;
  width: 120px; /* 设置上传区域的宽度 */
  height: 120px; /* 设置上传区域的高度 */
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar {
  width: 100%; /* 图片宽度自适应上传区域 */
  height: 100%; /* 图片高度自适应上传区域 */
  object-fit: cover; /* 保持图片比例并裁剪溢出部分 */
  border-radius: 6px; /* 圆角与上传区域一致 */
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>